package com.order.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.order.bean.Foods;
import com.order.bean.User;
import com.order.common.entiry.ResultCode;
import com.order.common.exception.CommonException;
import com.order.common.util.SqlSessionFactoryUtil;
import com.order.mapper.FoodsMapper;
import com.order.mapper.UserMapper;
import com.order.service.FoodsService;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.math.BigDecimal;
import java.util.List;

public class FoodsServiceImpl implements FoodsService {

    private FoodsMapper foodsMapper;

    private SqlSession sqlSession;

    private void closeMapper() {
        if (sqlSession != null) {
            sqlSession.close();
        }
    }

    private void initMapper() {
        SqlSessionFactory factory = SqlSessionFactoryUtil.getInstace();
        SqlSession sqlSession = factory.openSession(true);
        foodsMapper = sqlSession.getMapper(FoodsMapper.class);
    }

    @Override
    public boolean addFood(Foods food) {
        initMapper();
        boolean flag = foodsMapper.insert(food);
        closeMapper();
        return flag;
    }

    @Override
    public boolean deleteById(Integer id) {
        initMapper();
        boolean flag = foodsMapper.deleteById(id);
        closeMapper();
        return flag;
    }

    @Override
    public boolean deleteBatch(Integer[] foodIds) {
        for (Integer id : foodIds) {
            boolean b = this.deleteById(id);
            if (!b) return b;
        }
        return true;
    }

    @Override
    public boolean updateFood(Foods food) {
        initMapper();
        boolean flag = foodsMapper.update(food);
        closeMapper();
        return flag;
    }

    @Override
    public Foods selectFoodById(Integer id) {
        initMapper();
        Foods foods = foodsMapper.selectById(id);
        closeMapper();
        return foods;
    }

    @Override
    public List<Foods> selcetAllFoods() {
        initMapper();
        Foods food = new Foods();
        List<Foods> foods = foodsMapper.selectAll(food);
        closeMapper();
        return foods;
    }

    @Override
    public PageInfo<Foods> selcetFoodsPage(String foodName, Integer pageNum, Integer pageSize) {
        initMapper();
        Foods foods = new Foods();
        foods.setName(foodName);
        PageHelper.startPage(pageNum, pageSize);
        List<Foods> foodsList = foodsMapper.selectAll(foods);
        closeMapper();
        return PageInfo.of(foodsList);
    }

    @Override
    public void order(Integer foodId, Integer userId) {
        Foods foods = foodsMapper.selectById(foodId);
        double price = foods.getPrice();
    }
}
